import React, { useEffect, useState,useRef } from 'react';
import { Space, Table, Tag } from 'antd';
import type { TableProps } from 'antd';
import request from '../../api/request'
import { Button, Modal } from 'antd';
import type { FormProps } from 'antd';
import { Checkbox, Form, Input } from 'antd';
import type { PopconfirmProps } from 'antd';
import { message, Popconfirm } from 'antd';
import { Tabs } from 'antd';
function Index() {
  type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

const initialItems = [
  { label: 'Tab 1', children: 'Content of Tab 1', key: '1' },
  { label: 'Tab 2', children: 'Content of Tab 2', key: '2' },
  {
    label: 'Tab 3',
    children: 'Content of Tab 3',
    key: '3',
    closable: false,
  },
];
 const [activeKey, setActiveKey] = useState(initialItems[0].key);
  const [items, setItems] = useState(initialItems);
  const newTabIndex = useRef(0);

  const onChange = (newActiveKey: string) => {
    setActiveKey(newActiveKey);
  };

  const add = () => {
    const newActiveKey = `newTab${newTabIndex.current++}`;
    const newPanes = [...items];
    newPanes.push({ label: 'New Tab', children: 'Content of new Tab', key: newActiveKey });
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };

  const remove = (targetKey: TargetKey) => {
    let newActiveKey = activeKey;
    let lastIndex = -1;
    items.forEach((item, i) => {
      if (item.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const newPanes = items.filter((item) => item.key !== targetKey);
    if (newPanes.length && newActiveKey === targetKey) {
      if (lastIndex >= 0) {
        newActiveKey = newPanes[lastIndex].key;
      } else {
        newActiveKey = newPanes[0].key;
      }
    }
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };

  const onEdit = (
    targetKey: React.MouseEvent | React.KeyboardEvent | string,
    action: 'add' | 'remove',
  ) => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey);
    }
  };
    interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}
let [arr,setarr]=useState([])
let [title,settitle]=useState()
let [id,setid]=useState()
 const [form] = Form.useForm();
let getdata=()=>{
    request.get('/user/getMasterSelfBlog',{
        params:{
          
             pageNum:1,
 pageSize:10

        }
    }).then(res=>{ 
        console.log('列表',res)
        setarr(res.data.data)
    })
}
useEffect(()=>{
    getdata()
},[])
const columns: TableProps<DataType>['columns'] = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    render: (text) => <a>{text}</a>,
  },
  {
    title: 'Age',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: 'Address',
    dataIndex: 'tag',
    key: 'tag',
  },
   {
    title: '时间',
    dataIndex: 'update_time',
    key: 'update_time',
  },
  {
    title: 'Action',
    key: 'action',
    render: (_, record) => (
      <Space size="middle">
       <Button onClick={()=>bj(record)}>编辑</Button>
        <Popconfirm
    title="Delete the task"
    description="Are you sure to delete this task?"
    onConfirm={()=>sc(record.id)}
    onCancel={cancel}
    okText="Yes"
    cancelText="No"
  >
    <Button danger>删除</Button>
  </Popconfirm>
      </Space>
    ),
  },
];

// 新增
 const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
    form.resetFields();
    settitle('新增数据')
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
  console.log('Success:', values);
  if(title=='新增数据'){
    request.post('/user/addBlog',{
    title:values.title

  }).then(res=>{
    console.log('新增',res)
    getdata()
     setIsModalOpen(false);
alert('新增成功')
  })
  }
  else{
     request.put('/user/updateBlog',{
    blogId: id,
    title :values.title,
    editContent :values.title,
    showContent :values.title,
    tag :[],
    author: values.title


  }).then(res=>{
    console.log('编辑',res)
    getdata()
     setIsModalOpen(false);
alert('编辑成功')
  })
  }
  
};

const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
  console.log('Failed:', errorInfo);
};
// 删除
const confirm: PopconfirmProps['onConfirm'] = (e) => {
  console.log(e);
  message.success('Click on Yes');
};

const cancel: PopconfirmProps['onCancel'] = (e) => {
  console.log(e);
  message.error('Click on No');
};
const sc=(id)=>{
    request.delete('/user/deleteBlog',{
        params:{
             blogId:id

        }
    }).then(res=>{
        console.log('删除',res)
        getdata()
        alert('删除成功')
    })
}
// 编辑
const bj=(record)=>{
form.setFieldsValue(record);
 setIsModalOpen(true);
 setid(record.id)
}
// 搜索
const onFinish1: FormProps<FieldType>['onFinish'] = (values) => {
  console.log('搜索', values);

  getdata(values)
};

const onFinishFailed1: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
  console.log('Failed:', errorInfo);
};

  return (
    <div>
       <Tabs
      type="editable-card"
      onChange={onChange}
      activeKey={activeKey}
      onEdit={onEdit}
      items={items}
    />
          <Form
    name="basic"
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={onFinish1}
    onFinishFailed={onFinishFailed1}
    autoComplete="off"
  >
    <Form.Item<FieldType>
      label="Username"
      name="id"
      rules={[{ required: true, message: 'Please input your username!' }]}
    >
      <Input />
    </Form.Item>

    <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
       搜索
      </Button>
    </Form.Item>
  </Form>
         <>
      <Button type="primary" onClick={showModal}>
        新增
      </Button>
      <Modal
        title={title}
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
        form={form}
    name="basic"
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={onFinish}
    onFinishFailed={onFinishFailed}
    autoComplete="off"

    
  >
    <Form.Item<FieldType>
      label="Username"
      name="title"
      rules={[{ required: true, message: 'Please input your username!' }]}
    >
      <Input />
    </Form.Item>


    <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
        确定
      </Button>
    </Form.Item>
  </Form>
      </Modal>
    </>
     <Table<DataType> columns={columns} dataSource={arr} />
    </div>
  )
}

export default Index
